package bot

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"math/rand"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/sirupsen/logrus"
	logger "github.com/sirupsen/logrus"
)

type FileHandler struct {
}

func NewFileHandler() *FileHandler {
	return &FileHandler{}
}

func (program *FileHandler) Sleep() int {
	logger.Info("=== sleep started ")
	r := rand.Intn(3) + 2
	time.Sleep(time.Duration(r) * time.Second)
	logger.Info("=== sleep started ")
	return r
}

// 设置保存音频文件的目录
const (
	uploadPath = "./uploads"                           // 文件保存目录
	baseURL    = "http://localhost:8081/file/download" // 文件访问的基础 URL
)

func (fileHandler *FileHandler) UploadAudio(w http.ResponseWriter, r *http.Request) {
	logrus.Info("============================Upload")
	if r.Method != http.MethodPost {
		logrus.Error("Erorr request method must be post")
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	// 解析multipart form数据
	err := r.ParseMultipartForm(10 << 20) // 限制文件大小 10 MB
	if err != nil {
		logrus.Error("Error parsing form data: ", err)
		http.Error(w, "Error parsing form data", http.StatusBadRequest)
		return
	}

	for key, values := range r.Form {
		for _, value := range values {
			logrus.Infof("text  %s: %s\n", key, value)
		}
	}

	fileURL, filename := "", ""
	for key, files := range r.MultipartForm.File {
		for _, fileHeader := range files {
			logrus.Infof("file %s: %s\n", key, fileHeader.Filename)
			if file, err := fileHeader.Open(); err == nil {
				filename, err = fileHandler.saveFile(file, fileHeader)
				if err != nil {
					logrus.Error("====Error saving file: ", err)
					http.Error(w, "=====Error saving file", http.StatusInternalServerError)
					return
				}
				fileURL = fmt.Sprintf("%s?filename=%s", baseURL, fileHeader.Filename)
				break
			}
		}
	}

	logger.Debug(fileURL)
	var response = make(map[string]interface{})
	var body = make(map[string]interface{})
	body["data"] = map[string]string{"filePath": filename, "fileName": filename}
	body["code"] = 200
	body["msg"] = ""

	response["code"] = 200
	response["msg"] = "success"
	response["body"] = body
	jsonByte, _ := json.Marshal(response)
	str := string(jsonByte)
	logrus.Debug("upload audio ", str)
	io.WriteString(w, str)

	// 获取上传的文件
	// file, handler, err := r.FormFile("file")
	// if err != nil {
	// 	logrus.Error("Error get audio from formfile: ", err)
	// 	http.Error(w, "Error retrieving file", http.StatusBadRequest)
	// 	return
	// }
	// defer file.Close()

	// err = program.saveFile(file, handler)
	// if err != nil {
	// 	logrus.Error("Error saving file: ", err)
	// 	http.Error(w, "Error saving file", http.StatusInternalServerError)
	// 	return
	// }

	// // 创建上传目录
	// if err := os.MkdirAll(uploadPath, os.ModePerm); err != nil {
	// 	logrus.Error("Failed to create upload directory: ", err)
	// 	return
	// }
	// logrus.Info("2 ")

	// // 创建目标文件
	// dst, err := os.Create(filepath.Join(uploadPath, handler.Filename))
	// if err != nil {
	// 	logrus.Error("Create file eror: ", err)
	// 	http.Error(w, "Error saving file", http.StatusInternalServerError)
	// 	return
	// }
	// defer dst.Close()

	// logrus.Info("3 ")

	// // 将上传的文件内容复制到目标文件
	// if _, err := io.Copy(dst, file); err != nil {
	// 	logrus.Error("Error saving file: ", err)
	// 	http.Error(w, "Error saving file", http.StatusInternalServerError)
	// 	return
	// }
	// logrus.Info("4 ")

	// fileURL := fmt.Sprintf("%s?filename=%s", baseURL, handler.Filename)

	// logger.Debug(fileURL)

	// var response = make(map[string]interface{})
	// var body = make(map[string]interface{})
	// body["data"] = map[string]string{"msg": "upload success", "url": fileURL, "filename": handler.Filename, "status": "0"}

	// response["code"] = 200
	// response["msg"] = "success"
	// response["body"] = body
	// jsonByte, _ := json.Marshal(response)
	// str := string(jsonByte)
	// io.WriteString(w, str)
	// logrus.Info("5 ")

}

func (fileHandler *FileHandler) saveFile(file multipart.File, fileHeader *multipart.FileHeader) (string, error) {
	uploadFile := file
	if file == nil {
		var err error
		uploadFile, err = fileHeader.Open()
		if err != nil {
			logrus.Error("Error opening file: ", err)
			return "", err
		}
		defer uploadFile.Close()
	}
	// 创建上传目录
	if err := os.MkdirAll(uploadPath, os.ModePerm); err != nil {
		logrus.Error("Failed to create upload directory: ", err)
		return "", err
	}

	// 获取当前时间戳
	currentTime := time.Now().Unix()
	// 创建一个新的文件名，包含原始文件名和时间戳
	newFileName := fmt.Sprintf("%s_%d", fileHeader.Filename, currentTime)

	// 创建一个新的md5 hash对象
	hash := md5.New()

	// 将文件名和时间戳写入hash对象
	hash.Write([]byte(newFileName))

	// 计算字符串的MD5哈希值
	hashInBytes := hash.Sum(nil)

	// 将哈希值转换为16进制字符串
	md5String := fmt.Sprintf("%x", hashInBytes)

	// 创建最终的文件名，包含MD5哈希值
	logrus.Info("%s_%s", newFileName, md5String)

	newFileName = fmt.Sprintf("%s.mp3", md5String)

	// 创建目标文件
	dst, err := os.Create(filepath.Join(uploadPath, newFileName))
	if err != nil {
		logrus.Error("Create file eror: ", err)
		return "", err
	}
	defer dst.Close()

	// 将上传的文件内容复制到目标文件
	if _, err := io.Copy(dst, uploadFile); err != nil {
		logrus.Error("Error saving file: ", err)
		return "", err
	}
	logrus.Info("============ save file success ")
	return newFileName, nil
}

func (fileHandler *FileHandler) Download(w http.ResponseWriter, r *http.Request) {
	// 提取文件名
	// filename := filepath.Base(r.URL.Path)

	r.ParseForm()
	filename := r.Form.Get("filename")

	fmt.Print("filename ", filename)

	// 设置文件路径
	filePath := filepath.Join(uploadPath, filename)

	// 打开文件
	http.ServeFile(w, r, filePath)
}
